package com.blog.controller;


import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.blog.common.constant.Constant;
import com.blog.common.constant.ResultCode;

import com.blog.common.result.Result;
import com.blog.entity.User;

import com.blog.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

import org.springframework.beans.factory.annotation.Autowired;

import lombok.RequiredArgsConstructor;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.security.NoSuchAlgorithmException;

import java.util.Date;

@RestController
@Api(tags = "登陆接口")
@RequiredArgsConstructor
public class LoginController {


    @Autowired
    UserService userService;



    @PostMapping("/login")
    @ApiOperation(value = "用户登录接口", notes = "用户通过账号和密码进行登录")
    public Result login(@ApiParam(value = "用户信息", required = true) @RequestBody User user) throws NoSuchAlgorithmException {

        if (user.getAccount().isEmpty()) {
            return Result.error(ResultCode.USER_NEED_ACCOUNT);
        }
        if (user.getPassword().isEmpty()) {
            return Result.error(ResultCode.USER_NEED_PASSWORD);
        }
        // 登录逻辑
        User login = userService.login(user);
        //保存用户信息时，不保存密码
        login.setPassword(null);
        Algorithm algorithm = Algorithm.HMAC256(Constant.JWT_KEY);
        String token = JWT.create()
                .withClaim(Constant.USER_ID, user.getId())
                //过期时间
                .withExpiresAt(new Date(System.currentTimeMillis() + Constant.EXPIRE_TIME))
                .sign(algorithm);
        // 将用户名保存到缓存

        return Result.success(token);
    }

    @PostMapping("/register")
    @ApiOperation(value = "用户注册接口", notes = "新用户注册")
    public Result register(@ApiParam(value = "用户信息", required = true) @RequestBody User user) throws NoSuchAlgorithmException {

            // 注册逻辑

            return userService.register(user);
    }


    @GetMapping("/logout")
    @ApiOperation(value = "用户登出接口", notes = "用户登出")
    public Result logout() {
        // 登出逻辑
        return Result.success();
    }
}
